package com.e3roid.examples;

import android.view.MotionEvent;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.sprite.TextSprite;
import com.e3roid.event.TextInputListener;
import com.e3roid.opengl.RenderSurfaceView;

/**
 * Example for displaying soft input and getting result from user input. 
 * This example won't work on android emulator when soft input is disabled on the emulator.
 */
public class SoftInputExample extends E3Activity implements TextInputListener {

	private final static int WIDTH  = 320;
	private final static int HEIGHT = 480;
	
	private TextSprite label;

	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
		engine.requestFullScreen();
		return engine;
	}

	@Override
	protected RenderSurfaceView onLoadSurfaceView() {
		RenderSurfaceView view = super.onLoadSurfaceView();
		view.enableSoftInput(true);
		view.showSoftInput();
		view.hideSoftInputWhenDone(false);
		view.setTextInputListener(this);
		return view;
	}
	
	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		scene.setBackgroundColor(0.94f, 1.00f, 0.94f, 1);
		
		// Label width and height cannot be determined before loading Label object.
		// So if you want to move the label relative to the label size, use move() method
		// after creating Label instance.
		label.move((getWidth() - label.getWidth()) / 2, (getHeight() - label.getHeight()) / 2);
		
		scene.getTopLayer().add(label);
		return scene;
	}

	@Override
	public void onLoadResources() {
		// Set temporary text until receiving the text value.
		label = new TextSprite("____", 36, this);
	}
	
	/**
	 * Check if soft input is displayed.
	 */
	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
			getView().showSoftInput();
		}
		return false;
	}
	
	/**
	 * Called from InputConnection to indicate that the text is committed.
	 */
	@Override
	public boolean onCommitText(CharSequence text, int newCursorPosition) {
		label.setText(text.toString());
		return true;
	}
}